package com.jec.module.sysmanage.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.jec.module.sysmanage.dao.PrivilegeRepository;
import com.jec.module.sysmanage.dao.RoleRepository;
import com.jec.module.sysmanage.dao.UserRepository;
import com.jec.module.sysmanage.dao.UserResourceRepository;
import com.jec.module.sysmanage.entity.Privilege;
import com.jec.module.sysmanage.entity.Role;
import com.jec.module.sysmanage.entity.User;
import com.jec.module.sysmanage.entity.UserResource;
import com.jec.utils.EncryptUtils;


@Service
@Transactional
public class UserService {
	
	//@Resource
	//private UserDao userDao;
	
	@Autowired
	private UserRepository userRepository;
	
	//@Resource
	//private UserResourceDao userResourceDao;
	
	@Autowired
	private UserResourceRepository userResourceRepository;

	
	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	private PrivilegeRepository privilegeRepository;

	@Autowired
	private SysLogService sysLogService;

	@Transactional(propagation = Propagation.REQUIRED)
	public List<User> getAll()
	{
		return this.userRepository.findAll();
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public User login(String username, String password) {
		
		User user = userRepository.findByName(username);
		if(user == null)
			return null;
		
		String pswd = EncryptUtils.encryptMd5Password(password);
		if(user.getPassword().equals(pswd))
			return user;
		else
			return null;
	}

	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public boolean exist(String name){
		User user = userRepository.findByName(name);
		return user != null;
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public User saveNewUser(String username, String password, int role){
		
		if(userRepository.findByName(username) != null) {
			return null;
		}

		if(roleRepository.findOne(role) == null)
			return null;
		
		password = EncryptUtils.encryptPlainPassword(password);
		User user = new User();
		user.setCreateTime();
		user.setName(username);
		user.setPassword(password);
		user.setRoleId(role);
		userRepository.save(user);

		sysLogService.addLog("4-0","创建新用户" + username);
		return user;
	}

	@Transactional(readOnly = true)
	public User getUser(int userId){
		return userRepository.findOne(userId);
	}

	@Transactional
	public void saveUser(User user){
		userRepository.save(user);
	}

	@Transactional
	public boolean modifyUser(int userId, String name, Integer role, String password){
				
		User user = userRepository.findOne(userId);
		if(user == null) {
			return false;
		}
		
		
		if(!StringUtils.isEmpty(name)) {
			user.setName(name);
		}
		
		if(role != null) {
			user.setRoleId(role);
		}
		
		if(!StringUtils.isEmpty(password)) {
			user.setPassword(EncryptUtils.encryptPlainPassword(password));
		}
		
		userRepository.save(user);
		
		return true;

	}

	@Transactional
	public boolean removeUser(int id){
		
		User user = userRepository.findOne(id);
		if(user != null) {
			userRepository.delete(id);
			sysLogService.addLog("4-0","删除用户" + user.getName());
		}
		return true;
	}

	@Transactional(readOnly = true)
	public List<Role> getAllRoles(){
		return this.roleRepository.findAll();
		/*
		Search search = new Search(Role.class);
		search.addFilterGreaterThan("id", 0);
		return roleDao.search(search);
		*/
	}

	@Transactional
	public boolean removeRole(int role){

		List<User> users = userRepository.findByRoleId(role);
		if(!users.isEmpty())
			return false;
		
		//roleDao.removeById(role);
		roleRepository.delete(role);
		return true;
	}
	@Transactional(readOnly = true)
	public Role getUserRole(int userId){
		User user = userRepository.findOne(userId);
		return roleRepository.findOne(user.getRoleId());
	}
	
	public Role getUserRole(String name) {
		return roleRepository.findByName(name);
	}

	@Transactional
	public Role addUserRole(String name, String[] privilege){
		
		Role role = new Role();
		role.setName(name);
		role.setCreateTime(new Date());
		List<Privilege> privileges = new ArrayList<>();

		roleRepository.save(role);
		for(String pStr: privilege){
			if(pStr.length() > 0) {
				Privilege p = new Privilege();
				p.setValue(pStr);
				privileges.add(p);
				p.setRole(role.getId());
				//privilegeDao.save(p);
				privilegeRepository.save(p);
			}
		}
		role.setPrivilege(privileges);
		sysLogService.addLog("添加角色" + name);
		return role;
	}
	
	@Transactional
	public Role addUserRole(String name, Collection<String> privilege){
		
		Role role = new Role();
		role.setName(name);
		role.setCreateTime(new Date());
		List<Privilege> privileges = new ArrayList<>();

		roleRepository.save(role);
		for(String pStr: privilege){
			if(pStr.length() > 0) {
				Privilege p = new Privilege();
				p.setValue(pStr);
				privileges.add(p);
				p.setRole(role.getId());
				//privilegeDao.save(p);
				privilegeRepository.save(p);
			}
		}
		role.setPrivilege(privileges);
		sysLogService.addLog("添加角色" + name);
		return role;
	}

	@Transactional
	public boolean modifyRolePrivilege(int id, String[] privilege){
		Role role = roleRepository.findOne(id);
		if(role == null)
			return false;
		
		/*
		Search search = new Search(Privilege.class);
		search.addFilterEqual("role", id);
		List<Privilege> origin = privilegeDao.search(search);
		*/
		
		List<Privilege> origin = privilegeRepository.getByRole(id);
		
		int len1 = privilege.length;
		int len2 = origin.size();

		for(int i = 0; i< len2; i++){
			if(i<len1)
				origin.get(i).setValue(privilege[i]);
			else
				privilegeRepository.delete(origin.get(i));
		}

		for(int i=len2; i<len1; i++){
			Privilege p = new Privilege();
			p.setValue(privilege[i]);
			p.setRole(id);
			privilegeRepository.save(p);
		}

		sysLogService.addLog("修改角色" + role.getName() + "权限");
		return true;
	}

	@Transactional
	public boolean modifyRoleName(int id, String name){
		Role role = roleRepository.findOne(id);
		if(role == null)
			return false;
		String oldName = role.getName();

		if(oldName.equals(name))
		{
			sysLogService.addLog("角色未变更" + oldName);
			return false;
		}
		else
		{
			role.setName(name);
			roleRepository.save(role);

			sysLogService.addLog("修改角色名" + oldName);
			return true;
		}

	}
	
	public void initialize() {
		
		try {

		this.initResourceAndRole();
		
		//this.initUser();
		
		} catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Transactional
	private void initUser() {
		
		if(exist("admin")) return;
		
		Role r = getUserRole("系统管理员");
		
		User user = new User();
		user.setCreateTime();
		user.setName("admin");
		user.setPassword("388b741e27ab0cb96e7f2939fc3cd4b3");
		user.setRoleId(r.getId());
		userRepository.save(user);
		
	}
	
	@Transactional
	private void initRole() {
		
		List<UserResource> ress = this.userResourceRepository.findAll();
		String[] privileges = new String[ress.size()];
		for(int i = 0; i < ress.size(); i++) {
			privileges[i] = ress.get(i).getId();
		}
		
		Role r = getUserRole("系统管理员");
		if(r == null) {
			this.addUserRole("系统管理员", privileges);	
		}
		
	}
	
	@Transactional
	private void initResource() {
		
		UserResource res = null;
		
		/*
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0");
		res.setName("登录注册");
		res.setUrls("user/login,logout");
		res.setLog(true);
		userResourceDao.save(res);
		*/
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0-0");
		res.setName("网络监视");
		res.setUrls("network/topo,network/netunit/cardslot,network/netunit,network/state,network/card/type");
		res.setLog(false);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0-1");
		res.setName("业务监视");
		res.setUrls("business,business/list");
		res.setLog(false);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0-2");
		res.setName("设备监视");
		res.setUrls("device,device/state,device/port");
		res.setLog(false);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-0");
		res.setName("网络配置");
		res.setUrls("network/netunit/create,network/netunit/modify,network/netunit/connect/create,network/netunit/remove,network/card/modify");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-1");
		res.setName("用户数据配置");
		res.setUrls("config/userdata,config/save/userdata,config/remove/userdata,config/download/userdata");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-2");
		res.setName("设备配置");
		res.setUrls("device/create,device/modify,device/remove,device/port/create,device/port/modify,device/port/remove,config/terminalbusiness,config/save/terminalbusiness,config/remove/terminalbusiness,config/download/device/terminalbusiness,config/terminalkey,config/save/terminalkey,config/remove/terminalkey,config/download/device/terminalkey");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-3");
		res.setName("时钟配置");
		res.setUrls("config/clock,config/save/clock,config/remove/clock,config/download/clock");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-4");
		res.setName("时间配置");
		res.setUrls("config/download/time");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-5");
		res.setName("数字中继配置");
		res.setUrls("config/digittrunk,config/save/digittrunk,config/remove/digittrunk,config/download/digittrunk");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-6");
		res.setName("会议配置");
		res.setUrls("config/meeting,config/save/meeting,config/remove/meeting,config/download/meeting");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-7");
		res.setName("通令配置");
		res.setUrls("config/tongling,config/save/tongling,config/remove/tongling,config/download/tongling");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-8");
		res.setName("广播配置");
		res.setUrls("config/broadcast,config/save/broadcast,config/remove/broadcast,config/download/broadcast");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-9");
		res.setName("话务台配置");
		res.setUrls("config/phonestation,config/save/phonestation,config/remove/phonestation,config/download/phonestation");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("2");
		res.setName("录音软件");
		res.setUrls("business/record,business/record/history,business/record/current");
		res.setLog(false);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("3");
		res.setName("系统日志");
		res.setUrls("log,log/remove");
		res.setLog(false);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-0");
		res.setName("用户管理");
		res.setUrls("user,user/modify,user/remove,user/register");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-1");
		res.setName("角色管理");
		res.setUrls("user/roles,user/role/create,user/role/remove,user/role/modify");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-2");
		res.setName("修改密码");
		res.setUrls("user/password/modify");
		res.setLog(true);
		userResourceRepository.save(res);
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-3");
		res.setName("系统设置");
		res.setUrls("loadProperties,saveProperties");
		res.setLog(true);
		userResourceRepository.save(res);

	}
	

	private void initResourceAndRole() {
		
		List<String> adminPrivileges = new LinkedList<String>();
		//List<String> superPrivileges = Lists.newArrayList();
		
		UserResource res = null;
		
		/*
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0");
		res.setName("登录注册");
		res.setUrls("user/login,logout");
		res.setLog(true);
		userResourceDao.save(res);
		*/
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0-0");
		res.setName("网络监视");
		res.setUrls("network/topo,network/netunit/cardslot,network/netunit,network/state,network/card/type");
		res.setLog(false);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0-1");
		res.setName("业务监视");
		res.setUrls("business,business/list");
		res.setLog(false);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("0-2");
		res.setName("设备监视");
		res.setUrls("device,device/state,device/port");
		res.setLog(false);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-0");
		res.setName("网络配置");
		res.setUrls("network/netunit/create,network/netunit/modify,network/netunit/connect/create,network/netunit/remove,network/card/modify");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-1");
		res.setName("用户数据配置");
		res.setUrls("config/userdata,config/save/userdata,config/remove/userdata,config/download/userdata");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-2");
		res.setName("设备配置");
		res.setUrls("device/create,device/modify,device/remove,device/port/create,device/port/modify,device/port/remove,config/terminalbusiness,config/save/terminalbusiness,config/remove/terminalbusiness,config/download/device/terminalbusiness,config/terminalkey,config/save/terminalkey,config/remove/terminalkey,config/download/device/terminalkey");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-3");
		res.setName("时钟配置");
		res.setUrls("config/clock,config/save/clock,config/remove/clock,config/download/clock");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-4");
		res.setName("时间配置");
		res.setUrls("config/download/time");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-5");
		res.setName("数字中继配置");
		res.setUrls("config/digittrunk,config/save/digittrunk,config/remove/digittrunk,config/download/digittrunk");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-6");
		res.setName("会议配置");
		res.setUrls("config/meeting,config/save/meeting,config/remove/meeting,config/download/meeting");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-7");
		res.setName("通令配置");
		res.setUrls("config/tongling,config/save/tongling,config/remove/tongling,config/download/tongling");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-8");
		res.setName("广播配置");
		res.setUrls("config/broadcast,config/save/broadcast,config/remove/broadcast,config/download/broadcast");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-9");
		res.setName("话务台配置");
		res.setUrls("config/phonestation,config/save/phonestation,config/remove/phonestation,config/download/phonestation");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("1-10");
		res.setName("中继业务");
		res.setUrls("config/relay,config/save/relay,config/remove/relay,config/download/relay");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("2");
		res.setName("录音软件");
		res.setUrls("business/record,business/record/history,business/record/current");
		res.setLog(false);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("3");
		res.setName("系统日志");
		res.setUrls("log,log/remove");
		res.setLog(false);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("3-1");
		res.setName("系统日志删除");
		res.setUrls("log");
		res.setLog(false);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-0");
		res.setName("用户管理");
		res.setUrls("user,user/modify,user/remove,user/register");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-1");
		res.setName("角色管理");
		res.setUrls("user/roles,user/role/create,user/role/remove,user/role/modify");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-2");
		res.setName("修改密码");
		res.setUrls("user/password/modify");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
		
		res = new UserResource();
		res.setCreateDate(new Date());
		res.setId("4-3");
		res.setName("系统设置");
		res.setUrls("loadProperties,saveProperties");
		res.setLog(true);
		userResourceRepository.save(res);
		adminPrivileges.add(res.getId());
				
		Role roleAdmin = roleRepository.findByName("系统管理员");
		if(roleAdmin == null) {
			
			roleAdmin = new Role();
			roleAdmin.setName("系统管理员");
			roleAdmin.setCreateTime(new Date());
			roleAdmin = roleRepository.save(roleAdmin);
			
			List<Privilege> privileges = new ArrayList<>();
			for(String pStr: adminPrivileges){
				if(pStr.length() > 0) {
					Privilege p = new Privilege();
					p.setValue(pStr);
					privileges.add(p);
					p.setRole(roleAdmin.getId());
					privilegeRepository.save(p);
				}
			}
			
			roleAdmin.setPrivilege(privileges);
			
			//roleAdmin = this.addUserRole("系统管理员", adminPrivileges);	
		}
		
		
		User admin = userRepository.findByName("admin");
		if(admin == null) {			
			admin = new User();
			admin.setCreateTime();
			admin.setName("admin");
			admin.setPassword("388b741e27ab0cb96e7f2939fc3cd4b3");
			admin.setRoleId(roleAdmin.getId());
			userRepository.save(admin);
		}

	}
	
	public void patch081029() {
		
		UserResource res = userResourceRepository.findOne("3-1");
		if(res == null) {
			res = new UserResource();
			res.setCreateDate(new Date());
			res.setId("3-1");
			res.setName("系统日志删除");
			res.setUrls("log");
			res.setLog(false);
			res = userResourceRepository.save(res);
			
			Role roleAdmin = roleRepository.findByName("系统管理员");
			if(roleAdmin != null) {
				
				Privilege p = new Privilege();
				p.setValue("3-1");
				p.setRole(roleAdmin.getId());
				privilegeRepository.save(p);
				
				roleAdmin.getPrivilege().add(p);
				roleRepository.save(roleAdmin);
				
			}
		}
		

	}
	
	
	
}
